package com.sita.cfmoto.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.ActionMenuItem;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.BindVehicleRequest;
import com.sita.cfmoto.rest.model.request.ListVehicleIdRequest;
import com.sita.cfmoto.rest.model.response.ListVehicleResponse;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.activity.MainActivity;
import com.sita.cfmoto.utils.JsonUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.LogUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.sita.cfmoto.utils.VehicleUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class ActivationActivity extends AppCompatActivity {

    private final String TAG = ActivationActivity.class.getSimpleName();
    @Bind(R.id.btn_activate)
    Button mBtnActivate;

    public static Intent newIntent() {
        return new Intent(GlobalContext.getGlobalContext(), ActivationActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activate_vehicle);
        ButterKnife.bind(this);
        initToolbar(R.string.activate_vehicle);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        backToLogin();
    }

    private void backToLogin() {
        startActivity(LoginActivity.newIntent());
        this.finish();
    }

    protected void initToolbar(@StringRes int titleResId) {
        initToolbar(titleResId, false);
    }

    protected void initToolbar(@StringRes int titleResId, boolean isDarkMode) {
        View toolbarView = findViewById(R.id.toolbar);
        if (toolbarView != null) {
            if (toolbarView instanceof RelativeLayout) {
                ImageView backView = (ImageView) toolbarView.findViewById(R.id.btn_back);
                if (backView != null) {
                    backView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onOptionsItemSelected(new ActionMenuItem(ActivationActivity.this, 0, android.R.id.home, 0, 0, ""));
                        }
                    });
                }
                TextView titleView = (TextView) toolbarView.findViewById(R.id.toolbar_title);
                titleView.setText(getApplicationContext().getText(titleResId));

                if (isDarkMode) {
                    toolbarView.setBackgroundColor(getResources().getColor(R.color.black));
                    backView.setImageResource(R.drawable.arrow_left);
                    titleView.setTextColor(getResources().getColor(R.color.white));
                }
            }
        }
    }

    private void init() {
        if (PersistUtils.getUserStatus(LocalStorage.getAccountId()).equals(Constants.USER_STATUS_FETCHED)) {
//            activateBle();
        } else {
            fetchVehicle();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                backToLogin();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    void fetchVehicle() {

        final MaterialDialog dialog = new MaterialDialog.Builder(this).title(R.string.activate_vehicle).content(R.string.activating_vehicle)
                .progress(true, 15000)
                .build();
        dialog.show();

        ListVehicleIdRequest paramsJson = new ListVehicleIdRequest();
        paramsJson.sn = VehicleUtils.vehicleBean.vin;
        paramsJson.sncpy = VehicleUtils.vehicleBean.cpy;
        paramsJson.snpassword = VehicleUtils.vehicleBean.vinpwd;

        RestClient.getRestService().listVehicleId(paramsJson, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                LogUtils.d(TAG, "bind success" + restResponse.mErrorCode.toString() + "|" + restResponse.mData.toString());
                if (restResponse.mErrorCode.equals("0") && restResponse.mData != null) {
                    LogUtils.d(TAG, "bind success 1");
                    Gson gson = JsonUtils.getGson();
                    String str = gson.toJson(restResponse.mData);
                    ListVehicleResponse res = gson.fromJson(str, ListVehicleResponse.class);
                    LogUtils.d(TAG, "bind success2");
                    VehicleUtils.vehicleBean.controllerAddr = res.controller_address;
                    VehicleUtils.vehicleBean.controllerKey = res.controller_password;
                    VehicleUtils.vehicleBean.accountId = LocalStorage.getAccountId();

                    fetchOk();
                } else {
                    fetchFail();
                }

                dialog.dismiss();
            }

            @Override
            public void failure(RetrofitError error) {
                dialog.dismiss();
                fetchFail();
            }
        });
    }

    void fetchOk() {
        PersistUtils.updateVehicleBean(VehicleUtils.vehicleBean);
        PersistUtils.saveUserStatus(LocalStorage.getAccountId(), Constants.USER_STATUS_FETCHED);
    }

    void fetchFail() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.style(NormalDialog.STYLE_TWO)
                .titleLineColor(getResources().getColor(R.color.blue))
                .titleTextSize(20)
                .title(getString(R.string.warm_tips))
                .contentTextColor(getResources().getColor(R.color.black))
                .contentGravity(Gravity.CENTER)
                .content(getString(R.string.activation_error))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        // left
                        dialog.dismiss();
                        onBackToLoginActivity();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        // right
                        // try again
                        dialog.dismiss();
                        fetchVehicle(); // fetch again.
                    }
                });
    }

    void onBackToLoginActivity() {
        startActivity(new Intent(this, LoginActivity.class));
        this.finish();
    }


    private void onActivatedSuccess() {
        PersistUtils.saveUserStatus(LocalStorage.getAccountId(), Constants.USER_STATUS_ACTIVATED);
        VehicleUtils.vehicleBean.activated = true;
        PersistUtils.saveVehicleBean(VehicleUtils.vehicleBean);

        final NormalDialog dialog = new NormalDialog(this);
        dialog.content(getString(R.string.activation_success))//
                .btnNum(1)
                .btnText(getString(R.string.ok))//
                .show();

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                continueToMain();
                dialog.dismiss();
            }
        });

    }

    private void continueToMain() {
        startActivity(new Intent(this, MainActivity.class));
    }


    void sendActivateResult(final ProgressDialog progressDialog) {
//        final MaterialDialog dialog = new MaterialDialog.Builder(this).title(R.string.user_register).content(R.string.registering)
//                .progress(true, 15000)
//                .build();
//        dialog.show();

        BindVehicleRequest paramsJson = new BindVehicleRequest();
        paramsJson.vinId = VehicleUtils.vehicleBean.vin;
        paramsJson.vinCpy = VehicleUtils.vehicleBean.cpy;
        paramsJson.vinPassword = VehicleUtils.vehicleBean.vinpwd;

        RestClient.getRestService().bindVehicle(paramsJson, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                LogUtils.d(TAG, "bind success");
                if (restResponse.mErrorCode.equals("0")) {
                    bindSuccess();
                } else {
                    bindFailed();
                }
                progressDialog.dismiss();
            }

            @Override
            public void failure(RetrofitError error) {
                bindFailed();
                progressDialog.dismiss();
            }
        });
    }

    private void bindSuccess() {
        onActivatedSuccess();
    }

    private void bindFailed() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.style(NormalDialog.STYLE_TWO)
                .titleLineColor(getResources().getColor(R.color.blue))
                .titleTextSize(20)
                .title(getString(R.string.warm_tips))
                .contentTextColor(getResources().getColor(R.color.black))
                .contentGravity(Gravity.CENTER)
                .content(getString(R.string.binding_vehicle_error))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        // cancel
                        dialog.dismiss();
                        cancelBind();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        // try again
                        dialog.dismiss();
//                        tryAgainActivation();
                    }
                });
    }

    private void cancelBind() {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_ENABLE_BT ||
                requestCode == Constants.REQUEST_CONNECT_DEVICE) {

            if (requestCode == Constants.REQUEST_CONNECT_DEVICE) {

            } else if (requestCode == Constants.REQUEST_ENABLE_BT) {
                if (resultCode == Activity.RESULT_OK) {


                } else if (resultCode == Activity.RESULT_CANCELED) {

                }
            }
        }
    }
}
